/**
 *  jQuery Awesome 1.0.0
 *
 *  table.js
 *
 *  @author: cpChen（2015-10-14）
 */
(function($) {
    $.fn.table = function(obj, opt) {
        if (typeof obj == "string") {
            return $.fn.table.methods[obj](this, opt);
        }
        obj = obj || {};
        return this.each(function(){
            var _data = $.data(this, "table");
            var _opts;
            if(_data){
                _opts = $.extend(_data.options, obj);
                _data.options = _opts;
            } else {
                _opts = $.extend({},
                               $.extend({},$.fn.table.defaults,{queryParams:{}}),
                               $.fn.table.parseOptions(this), obj);
                // 组建table模型
                var _col = _tableModel(this);
                
            }
//            _5c(this);
//            _77(this);
//            _1e(this);
            if (_opts.data) {
                $(this).table("loadData", _opts.data);
            } else {
                var data = $.fn.table.parseData(this);
                if (data.total > 0) {
                    $(this).table("loadData", data);
                } else {
                    _opts.view.renderEmptyRow(this);
                }
            }
            _invoke(this);
        });
    };
    $.fn.table.methods = {
        reload: function(param){},
        loadData: function(jq, data) {
            return jq.each(function() {
                _b3(this, data);//TODO
                _17a(this);
            });
        },
        getData: function() {},
        getRows: function(jq) {
            return $.data(jq[0], "table").data.rows;
        },
        getRowIndex: function(row) {},
        getChecked: function() {},
        clearChecked: function() {},
    };
    $.fn.table.parseOptions = function(obj) {
        var t = $(obj);
        return $.extend({}, $.parser.parseOptions(obj, ["url", "idField", {
            rownumbers: "boolean",
        },{
            pagination: "boolean",
            pageSize: "number",
            pageNumber: "number"
        }]));
    };
    $.fn.table.parseData = function(obj) {
        var t = $(obj);
        var data = {
            total: 0,
            rows: []
        };
        var colspan = t.table("getColumnFields", true).concat(t.table("getColumnFields", false));//TODO 新增getColumnFields方法
        t.find("tbody tr").each(function(){
            data.total++;
            var row = {};
            for (var i =0; i < colspan.length; i++) {
                row[colspan[i]] = $(this).find("td:eq(" + i + ")").html();
            }
            data.rows.push(row);
        });
        return data;
    }
    $.fn.table.defaults = {
        columns: undefined,
        method: "post",
        idField: null,
        url: null,
        data: null,
        pagination: false,
        queryParams: {},
        loader: function(param, _success, _error) {
            var _opts = $(this).table("options");
            if(!opts.url){
                return false;
            }
            $.ajax({
                type: opts.method,
                url: opts.url,
                data: param,
                dataType: "json",
                success: function(data) {
                    _success(data);
                },
                error: function() {
                    _error.apply(this, arguments);
                }
            });
        },
        editors: {},  //TODO 增加一个editors对象 
        view: _view,
        onLoadError: function() {},
        onClickRow: function(index, data) {},
        onDblClickRow: function(index, data) {},
        onSelect: function(index, data) {},
        onCheck: function(index, data) {}
    };
    /**
     * 渲染table
     */
    var _view = {
        render: function(obj, body, flag) {
            var rows = $(obj).table("getRows");
            $(body).html(this.renderTable(obj, 0, rows, flag));
        },
        renderFooter: function() {},
        renderTable: function(obj, index, rows, flag) {
            var _data = $.data(obj, "table");
            var _opts = _data.options;
            if (flag) {
                if (! _opts.rownumbers) {
                    return "";
                }
            }
            var _html = [""];
        },
        renderRow: function(obj, columnFields, flag, index, row) {
            var _opts = $.data(obj, "table").options;
            var cc = [];
            if (flag && _opts.rownumbers) {
                var _ci = index + 1; // 计算当前行数
                //TODO 分页处理
                cc.push('<td>' + _ci + '</td>'); // 插入序号
            }
            for (var i = 0; i < columnFields.length; i++) {
                var _colName = columnFields[i];
                var _col = $(obj).table();
            }
        },
        refreshRow: function() {},
        updateRows: function() {},
        deleteRows: function() {},
        renderEmptyRow: function() {}
    }
    
    /**
     * 构建table模型
     */
    function _tableModel (obj) {
        function _columns () {
            var _col = [];
            $(obj).children("thead").each(function() {
                var opt = $.parser.parseOptions(this);
                $(this).find("tr").each(function() {
                    var _colTemp = [];
                    $(this).find("th").each(function() {
                        var th = $(this);
                        var col = $.extend({},$.parser.parseOptions(this, ["field", {
                            checkbox: "boolean"
                        }]),{
                            title: (th.html() || undefined),
                            hidden: (th.attr("hidden") ? true: undefined),
                            formatter: (th.attr("formatter") ? eval(th.attr("formatter")) : undefined)
                        });
                        if (col.width && String(col.width).indexOf("%") == -1) {
                            col.width = parseInt(col.width);
                        }
                        if (th.attr("editor")) {
                            var s = $.trim(th.attr("editor"));
                            if (s.substr(0, 1) == "{") {
                                col.editor = eval("(" + s + ")");
                            } else {
                                col.editor = s;
                            }
                        }
                        _colTemp.push(col);
                    });
                    _col.push(_colTemp);
                });
            });
            return [_col];
        }
        var cc = _columns();
        return {};
//        return {
//            panel: _58,
//            columns: cc[0],
//            dc: {
//                view: _59, //TODO
//                view1: _5a, //TODO
//                view2: _5b, //TODO
//                header1: _5a.children("div.datagrid-header").children("div.datagrid-header-inner"), //TODO
//                header2: _5b.children("div.datagrid-header").children("div.datagrid-header-inner"), //TODO
//                body1: _5a.children("div.datagrid-body").children("div.datagrid-body-inner"), //TODO
//                body2: _5b.children("div.datagrid-body"),
//                footer1: _5a.children("div.datagrid-footer").children("div.datagrid-footer-inner"), //TODO
//                footer2: _5b.children("div.datagrid-footer").children("div.datagrid-footer-inner") //TODO
//            }
//        }
    }
    
    /**
     * url请求&加载数据
     */
    function _invoke (obj, param) {
        var _opts = $.data(obj, "table").options;
        if (param) {
            _opts.queryParams = param;
        }
        var _param = $.extend({},_opts.queryParams);
        if (_opts.pagination) {
            $.extend(_param, {
                page: _opts.pageNumber || 1,
                rows: _opts.pageSize
            });
        }
        var _191 = _opts.loader.call(obj, _param,
        function(data) {
            $(obj).table("loadData", data);
        }, function() {
            opts.onLoadError.apply(obj, arguments);
        });
    }
    
    function _b3(obj, data) {
        var _data = $.data(obj, "datagrid");
        var _opts = _data.options;
        var dc = _data.dc;
        
        //渲染table
        _opts.view.render.call(_opts.view, obj, dc.body2, false);
    }
    
})(jQuery);